import DeptAPI from "@/api/system/dept-api";
import MenuAPI from "@/api/system/menu-api";
import areaData from "./area.json";
import OrgAPI from "@/api/org/org";
import { buildTree } from "@/utils/transform";
import UserAPI from "@/api/system/user-api";
import CustomersAPI from "@/api/custom/customers";
import VehicleCategoriesAPI from "@/api/config/car-type";
import VehicleNaturesAPI from "@/api/config/car-nature";
import VehiclePlateTypesAPI from "@/api/config/license-type";
import VehicleBrandModelsAPI from "@/api/config/vehicle-brand-models";
import DeptRoleAPI from "@/api/org/dep-role";
import BankAccountsAPI from "@/api/finance/bank-accounts/bank-accounts";
import VehicleInsuranceItemsAPI from "@/api/config/vehicle-insurance-items";

export const getDeptTree = (data?: any) => {
  const deptTree = ref({});
  DeptAPI.getOptions().then((res) => {
    deptTree.value = [
      {
        value: "0",
        label: "顶级部门",
        children: res,
      },
    ];

    if (data) {
      data.value = deptTree.value;
    }
  });
  return deptTree;
};

export const getMenuTree = (data?: any) => {
  const menuTree: any = ref([]);
  MenuAPI.getOptions().then((res) => {
    menuTree.value = res;
    if (data) {
      data.value = menuTree.value;
    }
  });
  return menuTree;
  // const roleId = row.id;
  // if (roleId) {
  //   assignPermDialogVisible.value = true;
  //   loading.value = true;
  //   checkedRole.value.id = roleId;
  //   checkedRole.value.name = row.name;
  //   // 获取所有的菜单
  //   menuPermOptions.value = await MenuAPI.getOptions();
  //   // 回显角色已拥有的菜单
  //   RoleAPI.getRoleMenuIds(roleId)
  //     .then((data) => {
  //       const checkedMenuIds = data;
  //       checkedMenuIds.forEach((menuId) => permTreeRef.value!.setChecked(menuId, true, false));
  //     })
  //     .finally(() => {
  //       loading.value = false;
  //     });
  // }
};

// 省市区列表-area就是选中的formData
export const getProvinceCityDistrictList = (area: any, formRef: any) => {
  const list = Object.keys(areaData).map((item) => {
    return {
      label: item,
      value: item,
    };
  });
  const provinceList = ref(list);

  // 市列表
  const cityList = computed(() => {
    return area.value.province
      ? Object.keys(areaData[area.value.province]).map((item) => {
          return {
            label: item,
            value: item,
          };
        })
      : [];
  });

  // 县区列表
  const districtList = computed(() => {
    return area.value.province && area.value.city
      ? Object.keys(areaData[area.value.province][area.value.city]).map((item) => {
          return {
            label: item,
            value: item,
          };
        })
      : [];
  });

  // 监听外部formData值得改变-area是没错得
  // 但是联动的值必须是SmForm表单内部的值进行联动

  const getSmFormData = () => {
    return formRef?.value?.getFormData();
  };

  // 编辑回显会有问题
  const changeProvince = () => {
    const smFormData = getSmFormData();
    if (smFormData) {
      smFormData.city = "";
      smFormData.district = "";
      area.value.city = "";
      area.value.district = "";
    }
  };

  const changeCity = () => {
    const smFormData = getSmFormData();
    if (smFormData) {
      smFormData.district = "";
      area.value.district = "";
    }
  };

  // // 监听省份变化
  // watch(
  //   () => area.value.province,
  //   (newVal) => {
  //     const smFormData = getSmFormData();
  //     if (smFormData) {
  //       smFormData.city = "";
  //       smFormData.district = "";
  //       area.value.city = "";
  //       area.value.district = "";
  //     }
  //     // area.street = "";
  //   }
  // );
  // 监听市区变化
  // watch(
  //   () => area.value.city,
  //   (newVal) => {
  //     const smFormData = getSmFormData();
  //     if (smFormData) {
  //       smFormData.district = "";
  //       area.value.district = "";
  //     }
  //     // area.district = "";
  //     // area.street = "";
  //   }
  // );
  // // 监听县区变化
  // watch(
  //   () => area.district,
  //   (newVal) => {
  //     area.street = "";
  //   }
  // );

  return {
    changeCity,
    changeProvince,
    provinceList,
    cityList,
    districtList,
  };
};

export const getUserList = (data?: any, params?: any) => {
  const userList: any = ref([]);
  UserAPI.getPage(params || { pageNum: 1, pageSize: 500 }).then((res: any) => {
    res?.list?.forEach((item: any) => {
      item.label = item.username; // realName
      item.value = item.id;
    });
    userList.value = res.list;
    if (data) {
      data.value = userList.value;
    }
  });
  return userList;
};

export const getOrganizationList = (data?: any) => {
  const organizationList: any = ref([]);
  OrgAPI.getOptions().then((res) => {
    const addLabelValue = (list: any[]) => {
      if (!list?.length) return;
      list.forEach((item) => {
        // item.value = item.id;
        // item.value = item.orgNo;
        // item.label = item.organizationName;
        item.label = item.organizationName;
        item.value = item.organizationNo;
        if (item?.children?.length) {
          addLabelValue(item.children);
        }
      });
    };

    addLabelValue(res);
    console.log(res, "res");
    organizationList.value = [
      {
        value: "0",
        label: "顶级组织",
        children: res,
      },
    ];
    if (data) {
      data.value = organizationList.value;
    }
  });
  return organizationList;
};

export const getDeptList = (data?: any, params?: any) => {
  const deptList = ref([]);
  DeptAPI.getOptions(params || { pageNum: 1, pageSize: 100 }).then((res: any) => {
    console.log(res, "res-dept");
    res?.list?.forEach((item: any) => {
      item.label = item.name;
      item.value = item.id;
    });
    deptList.value = res.list;
    if (data) {
      data.value = deptList.value;
      console.log(data.value, "data.value");
    }
    // deptList.value = [
    //   {
    //     value: "0",
    //     label: "顶级组织",
    //     children: res,
    //   },
    // ];
    // if (data) {
    //   data.value = deptList.value;
    // }
  });
  return deptList;
};

export const getDeptRoleList = (data?: any, params?: any) => {
  const deptRoleList = ref([]);
  const queryParams = { pageNum: 1, pageSize: 500 };
  Object.assign(queryParams, params);
  DeptRoleAPI.getPage(queryParams).then((res: any) => {
    res?.list?.forEach((item: any) => {
      item.label = item.name;
      item.value = item.id;
    });
    deptRoleList.value = res.list;
    if (data) {
      data.value = deptRoleList.value;
    }
  });
  return deptRoleList;
};

export const getUserMenusList = (data?: any, params?: any) => {
  const userMenusList: any = ref([]);
  MenuAPI.getUserMenus(params || {}).then((res: any) => {
    // const mockList = [
    //   { username: "发票1", id: "1" },
    //   { username: "发票2", id: "2" },
    // ];
    // mockList.forEach((item: any) => {
    //   item.label = item.username;
    //   item.value = item.id;
    // });
    // res = mockList;
    console.log(res, "res");

    const treeData = buildTree(res);
    userMenusList.value = [{ id: "0", name: "顶级菜单", children: treeData }];
    if (data) {
      data.value = userMenusList.value;
    }
  });
  return userMenusList;
};

export const getCustomerList = (data?: any, params?: any) => {
  const customerList: any = ref([]);
  CustomersAPI.getPage(params || { pageNum: 1, pageSize: 500 }).then((res: any) => {
    res?.list.forEach((item: any) => {
      item.label = item.customerName;
      item.value = item.id;
    });
    customerList.value = res.list || [];
    if (data) {
      data.value = customerList.value;
    }
  });
  return customerList;
};

export const getVehicleCategoryList = (data?: any, params?: any) => {
  const vehicleCategoryList: any = ref([]);
  VehicleCategoriesAPI.getPage(params || { pageNum: 1, pageSize: 500 }).then((res: any) => {
    res?.list.forEach((item: any) => {
      item.label = item.name;
      item.value = item.id;
    });
    vehicleCategoryList.value = res.list || [];
    if (data) {
      data.value = vehicleCategoryList.value;
    }
  });
  return vehicleCategoryList;
};

export const getVehicleNaturesList = (data?: any, params?: any) => {
  const vehicleNaturesList: any = ref([]);
  VehicleNaturesAPI.getPage(params || { pageNum: 1, pageSize: 500 }).then((res: any) => {
    res?.list.forEach((item: any) => {
      item.label = item.name;
      item.value = item.id;
    });
    vehicleNaturesList.value = res.list || [];
    if (data) {
      data.value = vehicleNaturesList.value;
    }
  });
  return vehicleNaturesList;
};

export const getVehiclePlateTypesList = (data?: any, params?: any) => {
  const VehiclePlateTypes: any = ref([]);
  VehiclePlateTypesAPI.getPage(params || { pageNum: 1, pageSize: 500 }).then((res: any) => {
    res?.list.forEach((item: any) => {
      item.label = item.name;
      item.value = item.id;
    });
    VehiclePlateTypes.value = res.list || [];
    if (data) {
      data.value = VehiclePlateTypes.value;
    }
  });
  return VehiclePlateTypes;
};

export const getVehicleBrandModelsList = (data?: any, params?: any) => {
  const vehicleBrandModelsList: any = ref([]);
  VehicleBrandModelsAPI.getPage(params || { pageNum: 1, pageSize: 500 }).then((res: any) => {
    res?.list.forEach((item: any) => {
      item.label = item.name;
      item.value = item.id;
    });
    vehicleBrandModelsList.value = res.list || [];
    if (data) {
      data.value = vehicleBrandModelsList.value;
    }
  });
  return vehicleBrandModelsList;
};

export const getVehicleInsuranceItemsList = (data?: any, params?: any) => {
  const vehicleInsuranceItemsList: any = ref([]);
  VehicleInsuranceItemsAPI.getPage(params || { pageNum: 1, pageSize: 500 }).then((res: any) => {
    res?.list.forEach((item: any) => {
      item.label = item.itemName;
      item.value = item.id;
    });
    vehicleInsuranceItemsList.value = res.list || [];
    if (data) {
      data.value = vehicleInsuranceItemsList.value;
    }
  });
  return vehicleInsuranceItemsList;
};

export const getBankAccountsList = (data?: any, params?: any) => {
  const bankAccountsList: any = ref([]);
  BankAccountsAPI.getPage(params || { pageNum: 1, pageSize: 500 }).then((res: any) => {
    res?.list.forEach((item: any) => {
      item.label = item.name;
      item.value = item.id;
    });
    bankAccountsList.value = res.list || [];
    if (data) {
      data.value = bankAccountsList.value;
    }
  });
  return bankAccountsList;
};

export const getCoordinateTypeList = (data?: any) => {
  const mockList = [
    { username: "模拟统筹分类1", id: "1" },
    { username: "模拟统筹分类2", id: "2" },
  ];
  const coordinateTypeList: any = ref([]);

  new Promise((resolve) => {
    setTimeout(() => {
      mockList.forEach((item: any) => {
        item.label = item.username;
        item.value = item.id;
      });
      coordinateTypeList.value = mockList;
      if (data) {
        data.value = coordinateTypeList.value;
      }

      resolve(mockList);
    }, 200);
  });

  return coordinateTypeList;
};

export const getInvoiceList = (data?: any) => {
  const invoiceList = ref({});
  DeptAPI.getOptions().then((res: any) => {
    const mockList = [
      { username: "发票1", id: "1" },
      { username: "发票2", id: "2" },
    ];
    mockList.forEach((item: any) => {
      item.label = item.username;
      item.value = item.id;
    });
    res = mockList;

    invoiceList.value = res;
    if (data) {
      data.value = invoiceList.value;
    }
  });
  return invoiceList;
};

export const getUnitList = (data?: any) => {
  const unitList = ref({});
  DeptAPI.getOptions().then((res: any) => {
    const mockList = [
      { username: "发票1", id: "1" },
      { username: "发票2", id: "2" },
    ];
    mockList.forEach((item: any) => {
      item.label = item.username;
      item.value = item.id;
    });
    res = mockList;

    unitList.value = res;
    if (data) {
      data.value = unitList.value;
    }
  });
  return unitList;
};
